package org.dromara.visitor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.visitor.domain.entity.VisConfig;
import org.dromara.visitor.mapper.VisConfigMapper;
import org.dromara.visitor.service.VisConfigService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class VisConfigServiceImpl extends ServiceImpl<VisConfigMapper, VisConfig> implements VisConfigService {
    @Resource
    private VisConfigMapper visConfigMapper;

    @Override
    public void setExpireTime(String buCode, Integer expireTime) {
        LambdaQueryWrapper<VisConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VisConfig::getBuCode, buCode);
        VisConfig visConfig = visConfigMapper.selectOne(queryWrapper);
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (visConfig == null) {
            visConfig = new VisConfig();
            visConfig.setBuCode(buCode);
            visConfig.setBuValue(expireTime);
            visConfig.setBuName("审核有效时限");
            visConfig.setBuUnit("min");
            visConfig.setCreateBy(loginUser.getUserId());
            visConfig.setUpdateBy(loginUser.getUserId());
            visConfig.setCreateTime(LocalDateTime.now());
            visConfig.setUpdateTime(LocalDateTime.now());
            visConfigMapper.insert(visConfig);
        }else {
            visConfig.setBuValue(expireTime);
            visConfig.setUpdateBy(loginUser.getUserId());
            visConfig.setUpdateTime(LocalDateTime.now());
            visConfigMapper.updateById(visConfig);
        }
    }

    @Override
    public Integer getExpireTime(String expireTime) {
        LambdaQueryWrapper<VisConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VisConfig::getBuCode, expireTime);
        VisConfig visConfig = visConfigMapper.selectOne(queryWrapper);
        if(visConfig != null){
            return visConfig.getBuValue();
        }
        return null;
    }
}
